﻿using Microsoft.SharePoint.Administration;
using System;
using System.Collections.Specialized;
using System.IO;
using System.Net;
using System.Text;
using System.Web.Services;
using System.Xml.Serialization;

using ggps.SharePoint.ws.Classes;

namespace ggps.SharePoint.ws
{
    public partial class CustomWebServices : WebService
    {
        [WebMethod]
        public rgWsPublicAfmMethodResponse GetVatDetails(String vat)
        {
            String username = getProperty(USERNAME);
            String password = getProperty(PASSWORD);
            String wsUrl = getProperty(WS_URL);

            string dataStr = String.Format(SoapUI_5_2_1_message, vat, username, password);

            rgWsPublicAfmMethodResponse afmMethodResponse = new rgWsPublicAfmMethodResponse();
            Envelope envResponse = new Envelope();
            byte[] buffer = Encoding.ASCII.GetBytes(dataStr);
            try
            {
                HttpWebRequest request = WebRequest.Create(wsUrl) as HttpWebRequest;
                request.Method = "POST";
                request.ContentType = "application/soap+xml";
                request.ContentLength = buffer.Length;
                Stream post = request.GetRequestStream();

                // post data and close connection
                post.Write(buffer, 0, buffer.Length);
                post.Close();
                HttpWebResponse response = request.GetResponse() as HttpWebResponse;
                using (Stream responsedata = response.GetResponseStream())
                {
                    StreamReader responsereader = new StreamReader(responsedata);
                    String responseStr = responsereader.ReadToEnd();
                    envResponse = processResponse<Envelope>(responseStr);
                }
                return envResponse.body.afmMethod;
            }
            catch (Exception e)
            {
                SPDiagnosticsService.Local.WriteTrace(0, 
                    new SPDiagnosticsCategory("gsis.ws", 
                        TraceSeverity.Unexpected, 
                        EventSeverity.Error), 
                        TraceSeverity.Unexpected, 
                        String.Format("Could not retrieve details for VAT#: {0}, because: {1}", vat, e.Message), 
                        e.ToString());

                afmMethodResponse.err = new pErrorRec_out();
                afmMethodResponse.err.errorCode = e.Message;
                afmMethodResponse.err.errorDescr = e.ToString();
            }
            return afmMethodResponse;
        }
        
        
        /*
         * get your own credentials by following the instructions found here: 
         * http://www.gsis.gr/gsis/info/gsis_site/PublicIssue/wnsp/wnsp_pages/wnsp.html */
        readonly static String USERNAME = "gsis.vat.username";// value=""/>
        readonly static String PASSWORD = "gsis.vat.password";// value=" "/>
        readonly static String WS_URL = "gsis.vat.wsurl";// value="https://www1.gsis.gr:443/webtax2/wsgsis/RgWsPublic/RgWsPublicPort"

        protected string getProperty(String key)
        {
            string response = String.Empty;
            try
            {
                NameValueCollection appSettings = System.Web.Configuration.WebConfigurationManager.AppSettings;
                // Get the appSettings section.
                if (appSettings.Count != 0)
                {
                    // foreach (string key in appSettings.Settings.AllKeys) 
                    response = appSettings[key] as String; 
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception raised: {0}",
                    e.Message);
            }
            return response;
        }

        private static T processResponse<T>(string responseStr)
        {
            responseStr = responseStr.Replace("<env:", "<").Replace("</env:", "</")
                                        .Replace("<m:", "<").Replace("</m:", "</")
                                         .Replace("<xsi:", "<").Replace("</xsi:", "</")
                                         .Replace("xmlns:m=\"http://gr/gsis/rgwspublic/RgWsPublic.wsdl\"", " ")
                                         .Replace("<Envelope", "<Envelope xmlns:m=\"http://gr/gsis/rgwspublic/RgWsPublic.wsdl\"")
                                         .Replace(" xsi:nil=\"true\"", "").Replace(" xsi:nil=\"false\"", "");
            // responseStr = responseStr.Replace("<m:rgWsPublicAfmMethodResponse", "<m:rgWsPublicAfmMethodResponse xmlns:env=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" ");
            // TextReader env_textReader = new StringReader(responseStr);
            TextReader afm_textReader = new StringReader(responseStr);

            XmlSerializer ser = new XmlSerializer(typeof(T));
            // XmlSerializer env_ser = new XmlSerializer(envResponse.GetType());
            T response = (T)ser.Deserialize(afm_textReader);
            return response;
        }

        public static String SoapUI_5_2_1_message = @"<env:Envelope xmlns:env=""http://schemas.xmlsoap.org/soap/envelope/""
xmlns:ns=""http://gr/gsis/rgwspublic/RgWsPublic.wsdl""
xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance""
xmlns:xsd=""http://www.w3.org/2001/XMLSchema""
xmlns:ns1=""http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"">
   <env:Header> 
   	<ns1:Security> 
   		<ns1:UsernameToken> 
   			<ns1:Username>{1}</ns1:Username> 
   			<ns1:Password>{2}</ns1:Password>
   		</ns1:UsernameToken> 
   	</ns1:Security> 
   </env:Header>
   <env:Body>
      <ns:rgWsPublicAfmMethod>
         <RgWsPublicInputRt_in>
            <ns:afmCalledBy></ns:afmCalledBy>
            <ns:afmCalledFor>{0}</ns:afmCalledFor>
         </RgWsPublicInputRt_in>
         <RgWsPublicBasicRt_out xsi:type=""ns:RgWsPublicBasicRtUser"">
			<ns:afm xsi:nil=""true""/>
			<ns:stopDate xsi:nil=""true""/>
			<ns:postalAddressNo xsi:nil=""true""/>
			<ns:doyDescr xsi:nil=""true""/>
			<ns:doy xsi:nil=""true""/>
			<ns:onomasia xsi:nil=""true""/>
			<ns:legalStatusDescr xsi:nil=""true""/>
			<ns:registDate xsi:nil=""true""/>
			<ns:deactivationFlag xsi:nil=""true""/>
			<ns:deactivationFlagDescr xsi:nil=""true""/>
			<ns:postalAddress xsi:nil=""true""/>
			<ns:firmFlagDescr xsi:nil=""true""/>
			<ns:commerTitle xsi:nil=""true""/>
			<ns:postalAreaDescription xsi:nil=""true""/>
			<ns:INiFlagDescr xsi:nil=""true""/>
			<ns:postalZipCode xsi:nil=""true""/>
		</RgWsPublicBasicRt_out>
		<arrayOfRgWsPublicFirmActRt_out xsi:type=""ns:RgWsPublicFirmActRtUserArray""/>
		<pCallSeqId_out xsi:type=""xsd:decimal"">0</pCallSeqId_out>
			<pErrorRec_out xsi:type=""ns:GenWsErrorRtUser"">
				<ns:errorDescr xsi:nil=""true""/>
				<ns:errorCode xsi:nil=""true""/>
			</pErrorRec_out>
      </ns:rgWsPublicAfmMethod>
   </env:Body>
</env:Envelope>";
    }
}
